package com.sharedmobility.servlet;

import com.google.gson.Gson;
import com.sharedmobility.dao.UserDAO;
import com.sharedmobility.model.User;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.annotation.WebServlet;

@WebServlet("/api/register")
public class RegisterServlet extends HttpServlet {
    private UserDAO userDAO;
    private Gson gson;

    @Override
    public void init() throws ServletException {
        userDAO = new UserDAO();
        gson = new Gson();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        try {
            // 获取请求参数
            Map<String, Object> requestData = gson.fromJson(request.getReader(), Map.class);
            String username = (String) requestData.get("username");
            String password = (String) requestData.get("password");
            String phone = (String) requestData.get("phone");

            // 验证参数
            if (username == null || username.trim().isEmpty()) {
                throw new Exception("用户名不能为空");
            }
            if (password == null || password.trim().isEmpty()) {
                throw new Exception("密码不能为空");
            }
            if (phone == null || phone.trim().isEmpty()) {
                throw new Exception("手机号不能为空");
            }

            // 检查用户名是否已存在
            if (userDAO.findByUsername(username) != null) {
                throw new Exception("用户名已存在");
            }

            // 创建新用户
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setPhone(phone);
            user.setBalance(new BigDecimal("0"));
            user.setCreditScore(100);
            user.setStatus(1);
            user.setRole("user");
            user.setIsAdmin(false);
            user.setIsMaintenanceStaff(false);
            user.setIsDriver(false);
            user.setIsCustomerService(false);
            user.setCreateTime(new Timestamp(System.currentTimeMillis()));

            boolean success = userDAO.create(user);
            if (!success) {
                throw new Exception("注册失败");
            }

            // 返回成功响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "注册成功");
            
            response.getWriter().write(gson.toJson(result));
        } catch (Exception e) {
            // 返回错误响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(gson.toJson(result));
        }
    }
} 